package com.alfred.mall.product.biz.service;

import com.alfred.common.framwork.util.StringUtil;
import com.alfred.mall.product.api.ProductSpuService;
import com.alfred.mall.product.api.bo.ProductAttrAndValuePairBO;
import com.alfred.mall.product.api.bo.ProductSkuDetailBO;
import com.alfred.mall.product.biz.convert.ProductSpuConvert;
import com.alfred.mall.product.biz.dao.ProductSkuMapper;
import com.alfred.mall.product.biz.dao.ProductSpuMapper;
import com.alfred.mall.product.biz.dataobject.ProductSkuDO;
import com.alfred.mall.product.biz.dataobject.ProductSpuDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@org.apache.dubbo.config.annotation.Service(validation = "true", version = "${dubbo.provider.ProductSpuService.version}")
public class ProductSpuServiceImpl implements ProductSpuService {

    @Autowired
    private ProductSkuMapper productSkuMapper;
    @Autowired
    private ProductSpuMapper productSpuMapper;
    @Autowired
    private ProductAttrServiceImpl productAttrService;

    @Override
    public List<ProductSkuDetailBO> getProductSkuDetailList(Collection<Integer> ids) {
        //根据skuId查询商品SKU
        List<ProductSkuDO> skus = productSkuMapper.selectByIds(ids);
        if (skus.isEmpty()) {
            return Collections.emptyList();
        }
        //根据spuId查询商品SPU
        List<ProductSpuDO> spus = productSpuMapper.selectByIds(skus.stream().map(ProductSkuDO::getSpuId).collect(Collectors.toSet()));
        if (spus.isEmpty()) {
            return Collections.emptyList();
        }
        //取出skus中的attr规格值
        Set<Integer> productAttrValueIds = new HashSet<>();
        skus.forEach(sku -> productAttrValueIds.addAll(StringUtil.splitToInt(sku.getAttrs(), ",")));

        List<ProductAttrAndValuePairBO> attrAndValuePairList = productAttrService.validProductAttrAndValue(productAttrValueIds,
                false);

        return ProductSpuConvert.INSTANCE.convert3(skus,spus,attrAndValuePairList);
    }
}
